package com.university.evaluation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.university.evaluation.common.ResponseResult;
import com.university.evaluation.domain.dto.EvaluationDTO;
import com.university.evaluation.entity.EvaluationSystem;
import com.university.evaluation.mapper.EvaluationSystemMapper;
import com.university.evaluation.service.EvaluationService;
import com.university.evaluation.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测评服务实现类
 */
@Slf4j
@Service
public class EvaluationServiceImpl extends ServiceImpl<EvaluationSystemMapper, EvaluationSystem> implements EvaluationService {

    @Autowired
    private EvaluationSystemMapper evaluationSystemMapper;

    @Override
    public ResponseResult<Void> testAuth() {
        try {
            // 检查用户是否已认证
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated() && 
                !authentication.getName().equals("anonymousUser")) {
                log.info("用户认证测试成功，用户: {}", authentication.getName());
                return ResponseResult.success("认证测试成功");
            } else {
                log.warn("用户未认证或认证无效");
                return ResponseResult.failure("用户未认证");
            }
        } catch (Exception e) {
            log.error("认证测试时发生异常", e);
            return ResponseResult.failure("认证测试失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseResult<Map<String, Object>> createEvaluation(EvaluationDTO evaluationDTO) {
        try {
            log.info("开始创建测评，测评名称: {}", evaluationDTO.getComments());
            
            // 创建测评体系实体
            EvaluationSystem evaluationSystem = new EvaluationSystem();
            // 这里根据实际的EvaluationDTO字段设置相应的值
            // 由于当前的EvaluationDTO字段与EvaluationSystem不完全匹配，使用默认值
            evaluationSystem.setSystemName("测评体系_" + System.currentTimeMillis());
            evaluationSystem.setDescription(evaluationDTO.getComments());
            evaluationSystem.setAcademicYear(String.valueOf(LocalDateTime.now().getYear()));
            evaluationSystem.setSemester(1);
            evaluationSystem.setStatus(0); // 0-未启用
            evaluationSystem.setCreateTime(LocalDateTime.now());
            
            boolean success = save(evaluationSystem);
            
            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("evaluationId", evaluationSystem.getId());
                result.put("systemName", evaluationSystem.getSystemName());
                result.put("createTime", evaluationSystem.getCreateTime());
                
                log.info("测评创建成功，ID: {}", evaluationSystem.getId());
                return ResponseResult.success("测评创建成功", result);
            } else {
                log.error("测评创建失败，数据库操作失败");
                return ResponseResult.failure("测评创建失败，请稍后再试");
            }
        } catch (Exception e) {
            log.error("创建测评时发生异常", e);
            return ResponseResult.failure("创建测评失败: " + e.getMessage());
        }
    }

    @Override
    public ResponseResult<Map<String, Object>> getEvaluationList() {
        try {
            log.info("获取测评列表");
            
            List<EvaluationSystem> evaluationList = list();
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", evaluationList);
            result.put("total", evaluationList.size());
            
            log.info("成功获取测评列表，共 {} 条记录", evaluationList.size());
            return ResponseResult.success("获取测评列表成功", result);
        } catch (Exception e) {
            log.error("获取测评列表时发生异常", e);
            return ResponseResult.failure("获取测评列表失败: " + e.getMessage());
        }
    }

    @Override
    public ResponseResult<Map<String, Object>> getEvaluationById(Long evaluationId) {
        try {
            log.info("获取测评详情，ID: {}", evaluationId);
            
            EvaluationSystem evaluation = getById(evaluationId);
            if (evaluation == null) {
                log.warn("未找到ID为 {} 的测评", evaluationId);
                return ResponseResult.failure("测评不存在");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("evaluation", evaluation);
            
            log.info("成功获取测评详情，ID: {}", evaluationId);
            return ResponseResult.success("获取测评详情成功", result);
        } catch (Exception e) {
            log.error("获取测评详情时发生异常，ID: {}", evaluationId, e);
            return ResponseResult.failure("获取测评详情失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseResult<Void> updateEvaluation(Long evaluationId, EvaluationDTO evaluationDTO) {
        try {
            log.info("更新测评信息，ID: {}", evaluationId);
            
            EvaluationSystem evaluation = getById(evaluationId);
            if (evaluation == null) {
                log.warn("未找到ID为 {} 的测评", evaluationId);
                return ResponseResult.failure("测评不存在");
            }
            
            // 更新测评信息
            if (evaluationDTO.getComments() != null) {
                evaluation.setDescription(evaluationDTO.getComments());
            }
            evaluation.setUpdateTime(LocalDateTime.now());
            
            boolean success = updateById(evaluation);
            
            if (success) {
                log.info("测评信息更新成功，ID: {}", evaluationId);
                return ResponseResult.success("测评信息更新成功");
            } else {
                log.error("测评信息更新失败，ID: {}", evaluationId);
                return ResponseResult.failure("测评信息更新失败，请稍后再试");
            }
        } catch (Exception e) {
            log.error("更新测评信息时发生异常，ID: {}", evaluationId, e);
            return ResponseResult.failure("更新测评信息失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseResult<Void> deleteEvaluation(Long evaluationId) {
        try {
            log.info("删除测评，ID: {}", evaluationId);
            
            EvaluationSystem evaluation = getById(evaluationId);
            if (evaluation == null) {
                log.warn("未找到ID为 {} 的测评", evaluationId);
                return ResponseResult.failure("测评不存在");
            }
            
            boolean success = removeById(evaluationId);
            
            if (success) {
                log.info("测评删除成功，ID: {}", evaluationId);
                return ResponseResult.success("测评删除成功");
            } else {
                log.error("测评删除失败，ID: {}", evaluationId);
                return ResponseResult.failure("测评删除失败，请稍后再试");
            }
        } catch (Exception e) {
            log.error("删除测评时发生异常，ID: {}", evaluationId, e);
            return ResponseResult.failure("删除测评失败: " + e.getMessage());
        }
    }

    @Override
    public ResponseResult<Map<String, Object>> getEvaluationPageList(Map<String, Object> params) {
        try {
            log.info("获取测评分页列表，参数: {}", params);
            
            // 解析分页参数
            int pageNum = Integer.parseInt(params.getOrDefault("pageNum", "1").toString());
            int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "10").toString());
            
            Page<EvaluationSystem> page = new Page<>(pageNum, pageSize);
            
            // 构建查询条件
            LambdaQueryWrapper<EvaluationSystem> wrapper = new LambdaQueryWrapper<>();
            
            // 根据系统名称模糊查询
            if (params.containsKey("systemName")) {
                wrapper.like(EvaluationSystem::getSystemName, params.get("systemName").toString());
            }
            
            // 根据状态查询
            if (params.containsKey("status")) {
                wrapper.eq(EvaluationSystem::getStatus, params.get("status"));
            }
            
            // 根据学年查询
            if (params.containsKey("academicYear")) {
                wrapper.eq(EvaluationSystem::getAcademicYear, params.get("academicYear").toString());
            }
            
            wrapper.orderByDesc(EvaluationSystem::getCreateTime);
            
            page = page(page, wrapper);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", page.getRecords());
            result.put("total", page.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("pages", page.getPages());
            
            log.info("成功获取测评分页列表，总记录数: {}", page.getTotal());
            return ResponseResult.success("获取测评分页列表成功", result);
        } catch (Exception e) {
            log.error("获取测评分页列表时发生异常", e);
            return ResponseResult.failure("获取测评分页列表失败: " + e.getMessage());
        }
    }

    @Override
    public ResponseResult<Map<String, Object>> getUserEvaluations() {
        try {
            log.info("获取用户参与的测评列表");
            
            // 获取当前用户信息
            String currentUser = UserContextUtil.getCurrentUsername();
            if (currentUser == null) {
                log.warn("获取当前用户信息失败");
                return ResponseResult.failure("用户未登录");
            }
            
            // 查询用户相关的测评（这里简化处理，返回所有启用状态的测评）
            LambdaQueryWrapper<EvaluationSystem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EvaluationSystem::getStatus, 1); // 仅查询启用状态的测评
            wrapper.orderByDesc(EvaluationSystem::getCreateTime);
            
            List<EvaluationSystem> userEvaluations = list(wrapper);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", userEvaluations);
            result.put("total", userEvaluations.size());
            result.put("currentUser", currentUser);
            
            log.info("成功获取用户参与的测评列表，用户: {}，共 {} 条记录", currentUser, userEvaluations.size());
            return ResponseResult.success("获取用户测评列表成功", result);
        } catch (Exception e) {
            log.error("获取用户参与的测评列表时发生异常", e);
            return ResponseResult.failure("获取用户测评列表失败: " + e.getMessage());
        }
    }
}